<template>
  <div class="map-page">
    <!-- Cesium地图容器 -->
    <div id="cesiumContainer" class="cesium-viewer"></div>
    <!-- 动态渲染统计组件（登录/未登录切换） -->
    <!-- 动态渲染统计组件（通过showStatistics控制显隐） -->
    <MapLoginStats v-if="userStore && showStatistics" />
    <MapUnloginStats v-else-if="!userStore && showStatistics" />
    <!-- 公共工具区：传递showStatistics状态并接收切换事件 -->
    <MapTools v-if="viewer" :viewer="viewer" v-model:showStats="showStatistics" :onStatsChange="handleStatsData"
      :onHindModelChange="handleModelChange" :modelData="modelData" :defaultData="defaultData" />


    <el-dialog v-model="isInfoDialog" :draggable="true" title="房间属性" width="850" center>
      <el-descriptions :column="2" :border="true" label-width="200px">
        <el-descriptions-item label="楼层" width="35%">
          {{ infoData.floor }}
        </el-descriptions-item>
        <el-descriptions-item label="房间号" width="35%">
          {{ infoData.roomNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="所属园区" width="35%">
          {{ infoData.parkName }}
        </el-descriptions-item>
        <el-descriptions-item label="所属楼栋" width="35%">
          {{ infoData.parkNuilding }}
        </el-descriptions-item>
        <el-descriptions-item label="入住企业" width="35%">
          {{ infoData.enterpriseName }}
        </el-descriptions-item>
        <el-descriptions-item label="面积（平方米）" width="35%">
          {{ infoData.area }}
        </el-descriptions-item>
        <el-descriptions-item label="入住状态" width="35%">

          <el-tag type="success" v-if="infoData.status">
            已入驻
          </el-tag>
          <el-tag type="primary" v-if="!infoData.status">
            空闲
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" width="35%">
          {{ infoData.remark }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isInfoDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
// 引入拆分的统计组件和工具组件
import MapLoginStats from '@/components/map/page/MapLoginStats.vue';
import MapUnloginStats from '@/components/map/page/MapUnloginStats.vue';
import MapTools from '@/components/map/MapTools.vue';
import auth from '@/components/utils/auth'
import { useMap3D } from '@/components/utils/UseMap3D'
import request from '@/api/request';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';

// 在组件卸载时设置标志
onUnmounted(() => {
  isComponentMounted.value = false;
});

// 添加一个标志来标记组件是否已卸载
const isComponentMounted = ref(true);
// 调用组合式函数
const {
  viewer, // 直接获取 useMap3D 内部的 viewer ref
  tileModels,
  set3Dtile,
  remove3Dtitle,
  zoomModel,
  setTerrain,
  pickedObject, // 直接获取 pickedObject
  addGltf,
  removeGltf,
} = useMap3D();

//当前显示的模型ID
const nowModelId = ref(null)
const nowModelItem = ref(null)//记录模型选择的是哪个，子模型清空后显示当前选择的模型
const isInfoDialog = ref(false)
const infoData = ref(null)
const handleModelChange = async (params, visable) => {
  if (visable == false) {
    await removeGltf(null)
  } else {
    if (params) {
      await removeGltf(params.floor)
    } else {
      await removeGltf(-1)
    }
  }

}
// 2. 定义接收子组件参数的方法
const handleStatsData = async (params) => {
  if (!isComponentMounted.value) return;
  // statsParams 就是子组件传回来的参数

  // 这里可处理参数，如更新父组件数据、执行业务逻辑等
  let loading = ElLoading.service({ text: '模型加载中...' })
  if (params == -1) {
    //缩放到图层
    if (nowModelId) {
      zoomModel(nowModelId.value)
    } else {
      ElMessage.error("还未加载模型")
    }
    loading.close()
  } else if (params) {
    if (nowModelId) {
      await remove3Dtitle(nowModelId.value)
      nowModelId.value = params.modelId
    }
    set3Dtile(params.modelFilePath, params.modelId, loading, params.height)
    if (params.childrenList && params.childrenList.length > 0) {
      nowModelItem.value = params
    }

    //加载gltf模型
    getGltf(params.floor)

  } else {
    await remove3Dtitle(nowModelId.value)
    nowModelId.value = nowModelItem.value.modelId
    set3Dtile(nowModelItem.value.modelFilePath, nowModelItem.value.modelId, loading, nowModelItem.value.height)
  }
};
const getGltf = (floor) => {
  request.get('/kml/getGltf', {
    params: {
      floor: floor
    }
  }).then(res => {
    res.data.forEach(item => {
      addGltf(item)
    });
  })
}

// 登录状态
const userStore = auth.isLoginIn();
// 新增：统计卡片显隐状态（默认显示）开发阶段
const showStatistics = ref(true);
const modelData = ref([])
const defaultData = ref([])

// 初始化地图
onMounted(() => {
  nextTick(() => {
    initCesium();
  });
});

// 初始化Cesium地图
const initCesium = () => {
  if (!isComponentMounted.value) return;
  // 监听登录状态变化，动态加载图层
  watch(() => userStore, (isLogin) => {
    isLogin ? loadPrivateLayers() : removePrivateLayers();
  },
    { immediate: true }
  );

  // 修改监听器，添加组件挂载检查
  watch(pickedObject, (newValue) => {
    if (!isComponentMounted.value) return;

    if (newValue) {
      isInfoDialog.value = true;
      infoData.value = newValue;
    } else {
      isInfoDialog.value = false;
    }
  });
}

// 登录后
const loadPrivateLayers = () => {
  if (!isComponentMounted.value) return;
  //登陆后在这里执行方法或者调用其他方法
  request.get("/model/getModel").then(res => {
    if (!isComponentMounted.value) return;
    if (res.success) {
      if (res.data.length > 0) {
        modelData.value = [...res.data]
        if (modelData.value.length > 0) {
          const targetIndex = modelData.value.findIndex(item => item.modelIsDefault === true);
          if (targetIndex > -1) {
            nowModelId.value = modelData.value[targetIndex].modelId
            nowModelItem.value = modelData.value[targetIndex]
            set3Dtile(modelData.value[targetIndex].modelFilePath, modelData.value[targetIndex].modelId, null, modelData.value[targetIndex].height)
            if (modelData.value[targetIndex].childrenList.length > 0) {
              defaultData.value = modelData.value[targetIndex].childrenList
            } else {
              defaultData.value = []
            }
          }
        }
      } else {
        ElMessage.info("没有查询到模型信息")
      }
    } else {
      ElMessage.error(res.message)
    }
  })
};

// 未登录/退出时
const removePrivateLayers = () => {
  //退出登陆后在这里执行方法或者调用其他方法
  /**
   * 2025年10月15日19:27:58，暂时先不做
   */
};
</script>

<style scoped>
.map-page {
  position: relative;
  width: 100%;
  height: 100%;
}

.cesium-container {
  width: 100%;
  height: 100%;
}
</style>